<?php

namespace app\api\model\dealer;

use app\common\model\dealer\Referee as RefereeModel;
use think\Db;
/**
 * 分销商推荐关系模型
 * Class Apply
 * @package app\api\model\dealer
 */
class Referee extends RefereeModel
{
    /**
     * 隐藏字段
     * @var array
     */
    protected $hidden = [];

    /**
     * 创建推荐关系
     * @param $user_id
     * @param $referee_id
     * @return bool
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public static function createRelation($user_id, $referee_id)
    {
        // 分销商基本设置
        $setting = Setting::getItem('basic');
        // 是否开启分销功能
        if (!$setting['is_open']) {
            return false;
        }
        // 自分享
        if ($user_id == $referee_id) {
            return false;
        }
        # 记录一级推荐关系
        # 判断当前用户是否已存在推荐关系
        if (self::isExistReferee($user_id)) {
            return false;
        }
        // 追溯寻找第一个有效的分销商
        $final_referee_id = self::findDealerReferee($referee_id);
        if ($final_referee_id === null) {
            return false; // 如果找不到有效的分销商，就不记录关系
        }
        // 新增关系记录
        $model = new self;
        $model->add($final_referee_id, $user_id, 1);
        self::buildRelationTree($referee_id, $user_id);
        return true;
    }
    /**
     * 往上递归查找最近的分销商用户
     * @param int $refereeId 初始推荐人ID
     * @param int $depth 最大递归层级，避免死循环
     * @return int|null 找到则返回 user_id，否则 null
     */
    public static function findDealerReferee($refereeId, $depth = 1000)
    {
        if ($depth <= 0 || $refereeId <= 0) {
            return null;
        }

        // 查询是否是分销商
        $dealer = Db::name('dealer_user')
            ->where(['user_id' => $refereeId, 'is_delete' => 0])
            ->find();
        if ($dealer) {
            return $refereeId;
        }

        // 不是分销商，继续往上找
        $upper = Db::name('dealer_relation_tree')
            ->where(['descendant_user_id' => $refereeId])
            ->value('ancestor_user_id');
        if (!$upper || $upper == $refereeId) {
            return null;
        }

        return self::findDealerReferee($upper, $depth - 1);
    }
    /**
     * 构建推荐关系树路径
     */
    public static function buildRelationTree($ancestorId, $userId, $wxappId = 10001)
    {
        $now = time();
        
        // 插入一级关系
        Db::name('dealer_relation_tree')->insert([
            'ancestor_user_id' => $ancestorId,
            'descendant_user_id' => $userId,
            'depth' => 1,
            'wxapp_id' => $wxappId,
            'create_time' => $now
        ]);

        // 查询该推荐人的所有上级路径
        $ancestors = Db::name('dealer_relation_tree')
            ->where('descendant_user_id', $ancestorId)
            ->select();

        foreach ($ancestors as $ancestor) {
            Db::name('dealer_relation_tree')->insert([
                'ancestor_user_id' => $ancestor['ancestor_user_id'],
                'descendant_user_id' => $userId,
                'depth' => $ancestor['depth'] + 1,
                'wxapp_id' => $wxappId,
                'create_time' => $now
            ]);
        }
    }
    /**
     * 新增关系记录
     * @param $dealer_id
     * @param $user_id
     * @param int $level
     * @return bool
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    private function add($dealer_id, $user_id, $level = 1)
    {
        // 新增推荐关系
        $wxapp_id = self::$wxapp_id;
        $create_time = time();
        $this->insert(compact('dealer_id', 'user_id', 'level', 'wxapp_id', 'create_time'));
        // 记录分销商成员数量
        User::setMemberInc($dealer_id, $level);
        return true;
    }

    /**
     * 是否已存在推荐关系
     * @param $user_id
     * @return bool
     * @throws \think\exception\DbException
     */
    private static function isExistReferee($user_id)
    {
        return !!self::get(['user_id' => $user_id]);
    }

}